package com.wanxi.app.service.user;

import com.wanxi.app.domain.dto.AppLogin;

import com.wanxi.app.domain.result.AppResult;
import com.wanxi.login.api.LoginFeign;
import com.wanxi.login.domain.dto.LoginDto;
import com.wanxi.login.domain.dto.LoginParamsDto;
import com.wanxi.login.domain.dto.PasswordDto;
import com.wanxi.login.domain.entity.TokenVo;
import com.wanxi.login.domain.result.LoginResult;
import com.wanxi.tool.api.ToolFeign;
import com.wanxi.tool.domain.result.ToolResult;
import com.wanxi.user.api.UserFeign;
import com.wanxi.user.domain.dto.UserInfoDto;
import com.wanxi.user.domain.result.UserResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author:wgy
 * @Data：2022/1/13 9:26
 */
@Service
public class LoginService {


    @Resource
    private LoginFeign loginFeign;

    @Resource
    private UserFeign userFeign;

    @Resource
    private ToolFeign toolFeign;


    public LoginResult<TokenVo> login(LoginParamsDto loginParamsDto) {
        LoginResult<TokenVo> login = loginFeign.login(loginParamsDto);
        if (login.getData() != null) {
            return login;
        }
        return LoginResult.failed();
    }


    public LoginResult<Boolean> add(AppLogin appLogin) {

          UserInfoDto userInfoDto = UserInfoDto.builder()
                    .email(appLogin.getEmail())
                    .phone(appLogin.getPhone())
                    .build();

            UserResult<Integer> userUserResult = userFeign.addUser(userInfoDto);
            try{
                if (userUserResult.getCode() != 200) {
                    return LoginResult.failed(false);
                }
                if (userUserResult.getData() > 0) {
                    LoginDto loginDto = LoginDto.builder()
                            .role(3)
                            .roleId(userUserResult.getData())
                            .password(appLogin.getPassword())
                            .username(appLogin.getUsername())
                            .build();
                    LoginResult<Boolean> loginResult = loginFeign.addLogin(loginDto);
                    if (loginResult.getData()) {
                        return LoginResult.success(loginResult.getData());
                    }
                }

            }catch (NullPointerException e){
                return LoginResult.failed("账号已被注册");
            }

        return LoginResult.addFailed();

    }

    public LoginResult<Boolean> updatePasswordById(PasswordDto passwordDto) {
        return loginFeign.updatePasswordByUserName(passwordDto);
    }

    public AppResult<String> fetchCode(String email) {

        ToolResult<String> email1 = toolFeign.getEmail(email);
        return AppResult.success("发送成功");

    }
}
